/*************************************************************************
    > File Name: tcpser.c
    > Author: Xing.Dai
    > Mail: Xing.Dai@aliyun.com 
    > Created Time: 2017-03-31 23:30
 ************************************************************************/

#include "unp.h"

void sig_chld(int signo)
{
	pid_t pid;
	int stat;
#if 0
	pid = wait(&stat);
	printf("child %d terminated.\n", pid);
#else 
	while((pid = waitpid(-1, &stat, WNOHANG)) > 0){
		printf("child %d terminated.\n", pid);
	}
#endif

	return;
}

int main(int argc, char **argv)
{
	int listenfd, connfd;
	pid_t childpid;
	socklen_t clilen;
	struct sockaddr_in servaddr, cliaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);
	
	Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	Signal(SIGCHLD, sig_chld);
	
	for( ; ; ){
		clilen = sizeof(cliaddr);
		if((connfd = accept(listenfd, (SA *)&cliaddr, &clilen)) < 0){
			if(errno == EINTR){
				printf("capture EINTR signal.\n");
				continue;
			} else {
				err_sys("accept error");
			}
		}

		if((childpid = Fork()) == 0){
			// Child process.
			Close(listenfd);
			str_echo(connfd);
			exit(0);
		}
		Close(connfd);

	}

}



